import { Component, OnInit } from '@angular/core';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { TimeConfigClass } from '../../../../common/common-config';
import { Check } from '../../../../common/check';
import { TemplateService } from '../template.service';
import { StorageService } from '../../../../common/storage.service';
declare const window;
@Component({
  selector: 'app-add-template',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css'],
  providers: [Check, TemplateService]
})


export class AddTemplateComponent implements OnInit {

  region: any[] = []; // 区域
  selectedRegion: any[] = []; // 选择区域
  template: any = {}; // 模板信息
  priceTemplate: any = {}; // 报价模板
  selectedPriceTemplate; // 选中后的报价模板
  payTemplate; // 交款模板
  selectedPayTemplate; // 选中后的交款模板
  constructionLimitDaysError; // 标准施工周期错误提示
  constructionLimitError; // 施工周期范围错误提示
  useAbleAreaError; // 适用面积错误提示
  priceTemplateError; // 报价模板错误提示
  payTemplateError; // 交款模板错误提示
  deliveryBatchNoError; // 送货批次错误提示
  teamId; // 编辑的id
  title: string = '创建模板';
  targetCars: any = [];
  filesTree: any = [];
  tempData: any = [];
  nameError;

  organizationOperationtData = []; // 所有组织数据对应的操作的数据
  organizationDialog = false; // 选择组织的弹窗
  organizationTree = []; // 组织tree原数据
  organizationError; // 错误提示
  selectedOrganizationTree = []; // 选中的组织数据

  W001 = false;
  constructor(private check: Check, private routeInfo: ActivatedRoute, private storage: StorageService,
    private templateService: TemplateService, private router: Router) {
  }

  ngOnInit() {
    // 初始化交款模板
    this.templateService.findTemplateList().then(
      data => {
        if (data.result) {
          this.payTemplate = data.data;
          console.log(this.payTemplate);
        } else {
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
    // // 初始化报价模板
    // this.templateService.findPriceTemplate().then(
    //   data => {
    //     if (data.result) {
    //       this.filesTree = data.data;
    //     } else {
    //       this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
    //     }
    //   }
    // );

  }
  // 初始化报价模板数据
  onClickPrice() {
    this.storage.loading();
    // 初始化报价模板
    console.log("this.targetCars",this.targetCars);
    this.templateService.findPriceTemplate(this.targetCars).then(
      data => {
        if (data.result) {
          this.filesTree = data.data;
          console.log(this.filesTree);
          this.W001 = true;
        } else {
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
        this.storage.loadout();
      }
    );
  }
  // 保存模板
  saveTement() {
    this.tempData = this.targetCars;
    if (this.tempData.length > 0) {
      this.priceTemplateError = '';
    }
    this['W001'] = false;
  }

  onRemove(data) {
    this.tempData = this.tempData.filter((item) => {
      if (item.id === data.id) {
        this.filesTree = [...this.filesTree, item];
        return false;
      } else { return true; }
    });
    this.targetCars = this.tempData.concat([]);
  }
  // 名称唯一性校验
  checkNameUnique(param) {
    if (!param) {
      this.nameError = '请输入名称';
      return;
    }

    this.templateService.checkNameUnique({ name: param }).then(
      result => {
        if (result.result) {
          this.nameError = '';
        } else {
          this.nameError = result.msg;
        }
      }
    );
  }
  // 校验交款模板
  payTemplateCk() {
    if (!(this.selectedPayTemplate && this.selectedPayTemplate['code'])) {
      this.payTemplateError = '请输入交款模板';
    } else {
      this.payTemplateError = '';
    }
  }
  /**
   * 保存数据
   */
  save() {
    this.storage.loading();
    let ids = new Array();
    let priceCode = new Array();
    let organizationCode = new Array();
    for (let index of this.tempData) {
      ids.push(index.id);
      priceCode.push(index.code);
    }
    for (let index of this.organizationOperationtData) {
      organizationCode.push(index.code);
    }
    this.template['priceTemplateId'] = ids;
    this.template['priceTemplateCode'] = priceCode;
    this.template['organizationCode'] = organizationCode;
    if (!this.checkSaveData()) {
      this.storage.loadout();
      return;
    }
    if (this.selectedPayTemplate) {
      this.template['payTemplateCode'] = this.selectedPayTemplate.code;
      this.template['payTemplateId'] = this.selectedPayTemplate.id;
    } else {
      delete this.template['payTemplateCode'];
      delete this.template['payTemplateId'];
    }
    this.templateService.save({ template: this.template }).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'success', detail: data.msg });
          this.router.navigate(['/saas/engineer/constructionconfig/template']);
        } else {
          this.nameError = data.msg;
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'error', detail: data.msg });
        }
      }
    );

  }
  // 校验标准施工周期
  checkLimitDays(param) {
    if (!param) {
      this.constructionLimitDaysError = '请输入标准施工周期';
      return;
    } else {
      this.constructionLimitDaysError = '';
    }
  }

  focuLimitDays() {
    this.constructionLimitDaysError = '';
  }
  // 校施工周期最小值
  checkDaysFrom(param) {
    if (!param) {
      this.constructionLimitError = '请输入施工周期范围';
      return;
    } else {
      if (param > this.template['constructionLimitDays']) {
        this.constructionLimitError = '施工范围最小值<=标准周期，施工范围最大值>=标准周期';
        return;
      } else {
        this.constructionLimitError = '';
      }
      if (param > this.template['constructionLimitDays']) {
        this.constructionLimitError = '施工范围最小值<=标准周期，施工范围最大值>=标准周期';
        return;
      } else {
        this.constructionLimitError = '';
      }
    }
  }
  // 校施工周期最大值
  checkDaysTo(param) {
    if (!param) {
      this.constructionLimitError = '请输入施工周期范围';
      return;
    } else {
      if (this.template['constructionLimitDaysFrom'] > param) {
        this.constructionLimitError = '施工范围最大值>=施工范围最小值';
        return;
      } else {
        this.constructionLimitError = '';
      }
      if (this.template['constructionLimitDays'] > param) {
        this.constructionLimitError = '施工范围最小值<=标准周期，施工范围最大值>=标准周期';
        return;
      } else {
        this.constructionLimitError = '';
      }
    }
  }
  // 校验 适用面积
  checkAbleArea(param) {
    if (!param) {
      this.useAbleAreaError = '请输入适用面积';
      return;
    } else {
      if (this.template['useAbleAreaFrom'] > this.template['useAbleAreaTo']) {
        this.useAbleAreaError = '适用面积最大值>=适用面积最小值';
        return;
      } else {
        this.useAbleAreaError = '';
      }
    }
  }
  checkAbleAreaTo(param) {
    if (!param) {
      this.useAbleAreaError = '请输入适用面积';
      return;
    } else {
      if (this.template['useAbleAreaFrom'] > this.template['useAbleAreaTo']) {
        this.useAbleAreaError = '适用面积最大值>=适用面积最小值';
        return;
      } else {
        this.useAbleAreaError = '';
      }
    }
  }
  // 请输入送货批次
  checkBatchNo(param) {
    if (!param) {
      this.deliveryBatchNoError = '请输入送货批次';
      return;
    } else {
      this.deliveryBatchNoError = '';
    }
  }
  // 数据校验
  checkSaveData(): boolean {
    let flag = true;
    if (!this.template['name']) {
      flag = false;
      this.nameError = '请输入名称';
    } else {
      this.nameError = '';
    }
    if (!this.template['constructionLimitDays']) {
      flag = false;
      this.constructionLimitDaysError = '请输入标准施工周期';
    } else {
      this.constructionLimitDaysError = '';
    }
    if (!this.template['constructionLimitDaysFrom'] && !this.template['constructionLimitDaysTo']) {
      flag = false;
      this.constructionLimitError = '请输入施工周期范围';
    } else {
      if (this.template['constructionLimitDaysTo'] < this.template['constructionLimitDays'] ||
        this.template['constructionLimitDaysFrom'] > this.template['constructionLimitDays']) {
        flag = false;
        this.constructionLimitError = '施工范围最小值<=标准周期，施工范围最大值>=标准周期';
      } else {
        this.constructionLimitError = '';
      }
    }
    if (!this.template['useAbleAreaFrom']) {
      flag = false;
      this.useAbleAreaError = '请输入适用面积';
    } else {
      this.useAbleAreaError = '';
    }
    if (!this.template['useAbleAreaTo']) {
      flag = false;
      this.useAbleAreaError = '请输入适用面积';
    } else {
      if (this.template['useAbleAreaFrom'] > this.template['useAbleAreaTo']) {
        flag = false;
        this.useAbleAreaError = '适用面积最大值>=适用面积最小值';
      } else {
        this.useAbleAreaError = '';
      }
    }
    if (this.template['priceTemplateId'].length === 0) {
      flag = false;
      this.priceTemplateError = '请选择报价模板';
    } else {
      this.priceTemplateError = '';
    }
    if (this.template['organizationCode'].length === 0) {
      flag = false;
      this.organizationError = '请选择适用组织';
    } else {
      this.organizationError = '';
    }
    if (!(this.selectedPayTemplate && this.selectedPayTemplate['code'])) {
      flag = false;
      this.payTemplateError = '请选择交款模板';
    } else {
      this.payTemplateError = '';
    }
    if (!this.template['deliveryBatchNo']) {
      flag = false;
      this.deliveryBatchNoError = '请输入送货批次';
    } else {
      this.deliveryBatchNoError = '';
    }
    return flag;
  }



  /**
   * 判断是不是正整数
   */
  checkNumber(data) {
    return (/^\d+$/g.test(data));
  }

  /**
   * 取消
   */
  returnBtn() {
    this.router.navigate(['/saas/engineer/constructionconfig/template']);
  }

  /**
   * 打开组织选择的弹框
   */
  selectOrganization() {
    // 所有已选的组织数据
    let codes = new Array();
    // 所有已选的物料数据
    let existenceData = [];
    existenceData = JSON.parse(JSON.stringify([...this.organizationOperationtData, ...this.organizationOperationtData]));
    // 所有已选的组织数据
    for (let index of existenceData) {
      codes.push(index.code);
    }
    // 调用ajax获取组织数据 并吧数据绑定到this.materialTree上
    // 组织树的数据源
    this.storage.loading();
    this.templateService.loadOrganization(codes).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.organizationTree = data.data;
          // 组织数据加载完成后展开树
          this.expandAll();
          this.organizationDialog = true;
        } else {
          this.storage.loadout();
          this.organizationTree = [];
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }
  expandAll() {
    this.organizationTree.forEach(node => {
      this.expandRecursive(node, true);
    });
  }

  /**
 * 组织树全部展开
 * @param node
 * @param isExpand
 */
  private expandRecursive(node, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.children) {
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }

  /**
 * 选中的组织数据
 */
  saveSelectedOrganization() {
    // this.selectedOrganizationTree = this.selectedOrganizationTree.filter((item) => {
    //   return !item.children || item.children.length <= 0;
    // });
    let materials = [];
    for (let item of this.selectedOrganizationTree) {
      let tem = { 'code': item.code, 'name': item.label };
      materials = [...materials, tem];
    }
    this.organizationOperationtData = JSON.parse(JSON.stringify([...this.organizationOperationtData, ...materials]));
    if (this.organizationOperationtData.length > 0) {
      this.organizationError = '';
    }
    this.selectedOrganizationTree = [];
    this.organizationDialog = false;
  }
  /**
 * 删除组织的方法
 * @param data 当前组织数据
 */
  removeOrganization(data) {
    this.organizationOperationtData = this.organizationOperationtData.filter((arr) => {
      if (arr.code === data.code) {
        return false;
      } else {
        return true;
      }
    });
  }
}

